﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shumei.EFCore.SimpleService
{
    public class BaseSimpleDAL<T>:ISimpleDAL<T> where T:class
    {
        private ShuMeiDBContext nContext;
        public BaseSimpleDAL()
        {
            nContext = new ShuMeiDBContext();
        }
        public DbSet<T> Entities { get { return nContext.Set<T>(); } }

        public T Add(T data,bool isSave = true)
        {
            nContext.Set<T>().Add(data);
            if(isSave) nContext.SaveChanges();
            return data;
        }

        public bool Update(T data, bool isSave = true)
        {
            nContext.Set<T>().Attach(data);
            nContext.Entry<T>(data).State = System.Data.Entity.EntityState.Modified;
            return isSave ? nContext.SaveChanges() > 0 : true;
        }

        public bool Delete(T data, bool isSave = true)
        {
            nContext.Set<T>().Attach(data);
            nContext.Entry<T>(data).State = System.Data.Entity.EntityState.Deleted;
            return isSave ? nContext.SaveChanges() > 0 : true;
        }


        public bool Exist(System.Linq.Expressions.Expression<Func<T, bool>> anyLambda)
        {
            return nContext.Set<T>().Any(anyLambda);
        }



        public int Save()
        {
            return nContext.SaveChanges();
        }
    }
}
